// 转换系数配置
const VALUE_CONVERSION_FACTOR = 60;  // 原始值需要除以此系数得到真实值

// Get measurement points from global variable
const validPointIds = new Set();
const measurementPoints = global.get('_MEASUREMENT_POINTS_');

// Add debug logging for measurement points configuration
debugLog('Loaded Measurement Points Configuration', measurementPoints);

if (measurementPoints) {
    Object.keys(measurementPoints).forEach(pointId => {
        validPointIds.add(pointId);
    });
    debugLog('Initialized Valid Point IDs', Array.from(validPointIds));
} else {
    node.error("No measurement points configuration found in global context - collection cannot proceed");
    return msg;
}

// Add validation for empty set
if (validPointIds.size === 0) {
    node.error("No valid point IDs found - check if _MEASUREMENT_POINTS_ global variable is properly initialized");
    return msg;
}

// 获取当前时间
const currentDate = new Date();
const currentHourKey = currentDate.toISOString().slice(0, 13) + ":00:00Z";
const currentDateString = currentDate.toISOString().slice(0, 10);

// 调试函数
function debugLog(msg, data) {
    node.warn(`DEBUG - ${msg}: ${JSON.stringify(data)}`);
}

// 初始化统计结构
function initializeStatistics() {
    // 获取现有统计数据
    const existingStats = global.get('_STATISTICS_');
    
    // 如果已存在统计数据，保留它
    if (existingStats) {
        debugLog('Using existing statistics structure', {
            hasPoints: Object.keys(existingStats.byMeasurementPoint || {}).length,
            lastUpdated: existingStats.lastUpdated
        });
        return existingStats;
    }
    
    // 只有在不存在时才创建新的统计结构
    const newStats = {
        byMeasurementPoint: {},
        byTimeDimension: {
            hourly: {},
            daily: {},
            weekly: {},
            monthly: {}
        },
        lastUpdated: null
    };
    
    debugLog('Created new statistics structure', null);
    return newStats;
}

// 初始化测点统计
function initializePointStats() {
    return {
        history: [],
        stats: { min: Infinity, max: -Infinity, sum: 0, count: 0, average: 0 }
    };
}

// 初始化小时统计
function initializeHourStats() {
    return {
        values: [],
        stats: { min: Infinity, max: -Infinity, sum: 0, count: 0, average: 0 }
    };
}

// 获取或初始化统计结构
let statistics = initializeStatistics();

// 1. 数据准备和验证
try {
    // 获取原始数据
    const rawDataPool = global.get('_DATA_POOL_');
    
    // 验证数据结构
    if (!rawDataPool || !rawDataPool.props) {
        node.error("Invalid or empty data pool");
        debugLog('Data Pool Status', {
            hasDataPool: !!rawDataPool,
            hasProps: rawDataPool ? !!rawDataPool.props : false
        });
        // 保持现有统计数据不变
        global.set('_STATISTICS_', statistics);
        return msg;
    }

    debugLog('Raw Props', rawDataPool.props);
    debugLog('Available Point IDs in Data', Object.keys(rawDataPool.props));

    // 创建一个安全的数据副本，只包含配置中的测点
    const validData = {};
    const skippedPoints = {};
    
    Object.keys(rawDataPool.props).forEach(pointId => {
        if (validPointIds.has(pointId)) {
            const value = rawDataPool.props[pointId];
            // 确保值不是undefined或null
            if (value !== undefined && value !== null) {
                // 如果值是对象（比如bits结构），获取orig值
                if (typeof value === 'object' && value.hasOwnProperty('orig')) {
                    validData[pointId] = value.orig;
                } else {
                    validData[pointId] = value;
                }
            }
        } else {
            skippedPoints[pointId] = rawDataPool.props[pointId];
        }
    });

    debugLog('Points Being Processed', {
        validPoints: Object.keys(validData),
        skippedPoints: Object.keys(skippedPoints),
        configuredPoints: Array.from(validPointIds)
    });

    // 如果没有有效数据，直接返回
    if (Object.keys(validData).length === 0) {
        node.warn("No valid measurement points data found - check if point IDs match between data and configuration");
        return msg;
    }

    // 确保必要的数据结构存在
    if (!statistics.byMeasurementPoint) {
        statistics.byMeasurementPoint = {};
    }
    if (!statistics.byTimeDimension || !statistics.byTimeDimension.hourly) {
        statistics.byTimeDimension = {
            hourly: {},
            daily: {},
            weekly: {},
            monthly: {}
        };
    }

    // 3. 实时数据处理
    Object.entries(validData).forEach(([pointId, value]) => {
        try {
            // 确保测点ID有效
            if (!validPointIds.has(pointId)) {
                debugLog(`Point ${pointId} not in valid points list`, null);
                return;
            }

            // 转换为数值并验证
            let rawValue = Number(value);
            if (isNaN(rawValue)) {
                debugLog(`Invalid numeric value for point ${pointId}`, value);
                return;
            }

            // 转换为真实值
            const latestValue = Number((rawValue / VALUE_CONVERSION_FACTOR).toFixed(2));

            // 初始化或获取测点数据
            if (!statistics.byMeasurementPoint[pointId]) {
                statistics.byMeasurementPoint[pointId] = initializePointStats();
            }

            const pointStats = statistics.byMeasurementPoint[pointId];

            // 确保history数组存在
            if (!Array.isArray(pointStats.history)) {
                pointStats.history = [];
            }

            // 清理和更新历史数据
            pointStats.history = pointStats.history
                .filter(entry => entry && entry.timestamp && entry.timestamp.startsWith(currentDateString));

            // 添加新数据
            pointStats.history.push({
                value: latestValue,
                timestamp: currentDate.toISOString()
            });

            // 更新统计指标
            pointStats.stats.count++;
            pointStats.stats.sum = Number((pointStats.stats.sum + latestValue).toFixed(2));
            pointStats.stats.average = Number((pointStats.stats.sum / pointStats.stats.count).toFixed(2));
            pointStats.stats.min = Number(Math.min(pointStats.stats.min, latestValue).toFixed(2));
            pointStats.stats.max = Number(Math.max(pointStats.stats.max, latestValue).toFixed(2));

            // 确保hourly数据结构存在
            if (!statistics.byTimeDimension.hourly[currentHourKey]) {
                statistics.byTimeDimension.hourly[currentHourKey] = {};
            }

            if (!statistics.byTimeDimension.hourly[currentHourKey][pointId]) {
                statistics.byTimeDimension.hourly[currentHourKey][pointId] = initializeHourStats();
            }

            const hourData = statistics.byTimeDimension.hourly[currentHourKey][pointId];
            hourData.values.push(latestValue);
            hourData.stats.count++;
            hourData.stats.sum = Number((hourData.stats.sum + latestValue).toFixed(2));
            hourData.stats.average = Number((hourData.stats.sum / hourData.stats.count).toFixed(2));
            hourData.stats.min = Number(Math.min(hourData.stats.min, latestValue).toFixed(2));
            hourData.stats.max = Number(Math.max(hourData.stats.max, latestValue).toFixed(2));

        } catch (pointError) {
            node.warn(`Error processing point ${pointId}: ${pointError.message}`);
        }
    });

    // 4. 实时数据清理（仅保留当天hourly）
    if (statistics.byTimeDimension && statistics.byTimeDimension.hourly) {
        statistics.byTimeDimension.hourly = Object.fromEntries(
            Object.entries(statistics.byTimeDimension.hourly)
                .filter(([key]) => key.startsWith(currentDateString))
        );
    }

    // 在处理完成后，确保我们保存了所有统计数据
    statistics.lastUpdated = currentDate.toISOString();
    global.set('_STATISTICS_', statistics);
    debugLog('Final Statistics Status', {
        pointsCount: Object.keys(statistics.byMeasurementPoint).length,
        hourlyDataPoints: Object.keys(statistics.byTimeDimension.hourly).length,
        timestamp: statistics.lastUpdated,
        samplePoints: Object.keys(statistics.byMeasurementPoint).slice(0, 3) // 显示前3个点作为样本
    });

} catch (error) {
    node.error("Error processing data: " + error.message);
    node.warn(error.stack);
}

return msg;